package com.example.operation.musicpaster;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.widget.TextView;
import android.widget.Toast;

import com.example.test_webview_demo.utils.X5WebView;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.openqa.selenium.*;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;

import io.selendroid.common.SelendroidCapabilities;


/**
 * Created by hsj on 2017/8/17.
 */

public class MyWebview extends X5WebView {

    String tag = "MyWebView";
    Activity myActivity;
    public Handler handler = new Handler();

    public MyWebview(Context context) {
        super(context);
        init(context);
    }

    public MyWebview(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    String only1;

    public String getOnly1() {
        return only1;
    }

    public interface LoadWebFinish {
        void loadwebfinish(String url);
    }

    LoadWebFinish loadWebFinish;

    public MyWebview setLoadWebFinish(LoadWebFinish loadWebFinish) {
        this.loadWebFinish = loadWebFinish;
        return this;
    }

    public float step = 1;

    public void setOnceSearchPlay(String onceSearchPlay) {
        this.onceSearchPlay = onceSearchPlay;
    }

    String onceSearchPlay = "false";
    String thenAuto = "false";

    public float getStep() {
        return step;
    }

    public void setThenAuto(String thenAuto) {
        this.thenAuto = thenAuto;
    }

    public String getThenAuto() {
        return thenAuto;
    }

    void init(final Context context) {
        myActivity = (AppCompatActivity) context;

        setWebViewClient(new com.tencent.smtt.sdk.WebViewClient() {


            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                return super.shouldOverrideUrlLoading(webView, s);
            }

            public void onLoadResource(WebView view, final String url) {
                String furl = url;
                if (furl.contains("http://music.163.com/m/song")) {
                    furl += "&autoplay=true";
                }
                super.onLoadResource(view, furl);
                if (step == 1) {
                    if (furl.contains("m.baidu.com")&&!(furl.endsWith(".js")||furl.endsWith(".ico")||furl.endsWith(".png"))) {

                        new Thread() {
                            String content;

                            @Override
                            public void run() {
                                super.run();
                                content = Http.myGetHttpFile2(url);
                                if (content.contains("最全音乐试听播放")) {
                                    String s = "https://m.baidu.com/sugrec";
                                    int clue = content.indexOf("最全音乐试听播放");
                                    int signstart = content.indexOf("https://m.baidu.com/from=0/bd_page_type", clue);
                                    int signend = content.indexOf("\"", signstart + 1);
                                    only1 = content.substring(signstart, signend).replaceAll("&amp;", "&");

//                                    if (step >= 2) {
//                                        if (loadWebFinish != null) {
//                                            loadWebFinish.loadwebfinish(url);
//                                        }
//                                    }
loadUrl(only1);
                                    step++;
                                }
//https://m.baidu.com/from=0/bd_page_type=1/ssid=0/uid=0/pu=usm%405%2Csz%40320_1004%2Cta%40iphone_2_5.1__/baiduid=EF4826D1C6F0E2416523391E6D26F097/w=0_10_/t=iphone/l=1/tc?ref=www_iphone&lid=7386692725888128695&order=1&extra=mc_multi&isAtom=1&is_baidu=0&tj=2c9_1_0_10_l3&wd=&eqid=6682cde5d7861800100000035c923df2&w_qd=IlPT2AEptyoA_yk5z35buAWuAiaXqodBoDxisfK0&tcplug=1&sec=37213&di=6c64c68908ad2626&bdenc=1&nsrc=IlPT2AEptyoA_yixCFOxXnANedT62v3IGw3CLCsKQ7zh95qshbWxBdkfEFXgL8WVZpLPvWL0sakCx8Gc0W9z7xQKa3grczVuomja90iqxcCLHxJErc1v0cKHG5Ya53XqmOh6
  //https://music.163.com/#/song?id=375328&autoplay=true&market=baiduqk

//                        https://m.baidu.com/from=0/bd_page_type=1/ssid=0/uid=0/pu=usm%404%2Csz%40320_1001%2Cta%40iphone_2_6.0_24_44.0/baiduid=C613F49E54817A34FCC776E1CC439227/w=0_10_/t=iphone/l=1/tc?ref=www_iphone&lid=7091101497560372291&order=2&extra=mc_multi&isAtom=1&is_baidu=0&tj=2c9_2_0_10_l3&wd=&eqid=6268a73de4539400100000035c85df23&w_qd=IlPT2AEptyoA_ykx5xUd5fJsR5k4tXxAnyhc&tcplug=1&sec=36988&di=0def2979232dd0dc&bdenc=1&tch=124.90.314.510.1.762&nsrc=IlPT2AEptyoA_yixCFOxXnANedT62v3IGw3CLCsKQ7zh95qshbWxBdkfEFXgL8WVZpLPvWL0sakCwH_i_GUz7xQKa3grczVuomja90iqxcCLHxJErc1v0cKHG5Ya53XqmOh6
//                        https://s1.music.126.net/style/favicon.ico?v20180307
//                    https://xiongzhang.baidu.com/xzhstatistics/rp?pid=66&sub_pid=1&log_type=1&s_type=pfm&mlt=0&dt=140&s_id=1582028769404989&pt=online&_t=1552277341627
//                    http://music.163.com/m/song?id=306971&autoplay=true&market=baiduqk


                            }
                        }.start();
                    }
                }
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                step++;
                if (step >= 2) {
                    if (loadWebFinish != null) {
                        loadWebFinish.loadwebfinish(url);
                    }
                }

            }

        });
        setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDatabaseEnabled(true);
        //取得缓存路径
        String path = context.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        //设置路径
        webSettings.setDatabasePath(path);
        //设置支持DomStorage
        webSettings.setDomStorageEnabled(true);
        //设置存储模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置缓存
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setNeedInitialFocus(true);
        webSettings.setUseWideViewPort(true);
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK
                        && event.getAction() == KeyEvent.ACTION_DOWN) && canGoBack()) {
                    goBack();
                    return true;
                }
                return false;
            }
        });

    }


    public class MyPermission extends AppCompatActivity {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
            super.onCreate(savedInstanceState, persistentState);
            storagepermission();
        }

        //6.0动态获取权限
        public void storagepermission() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                    PackageManager.PERMISSION_GRANTED) {
//            new Thread(saveFileRunnable).start();
            } else {
                //需要申请权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }

        //如果权限允许了，则不会走下面
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case 1:
                    if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {//点击允许后走下面,只走一次
                        // 获取权限成功。操作继续。
//                    new Thread(saveFileRunnable).start();
                    } else if (grantResults[0] == PackageManager.PERMISSION_DENIED) {//点击拒绝后走下面，以后只要权限未开，就每次都走这个方法
                        Toast.makeText(myActivity, "图片保存失败！" + "\n" + "贯众云医的存储权限被关闭，请在设置里打开存储权限", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    //webview返回事件
    @JavascriptInterface
    public void webviewback() {
        if (canGoBack()) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    goBack();
                }
            });
        } else {
            myActivity.onBackPressed();
        }
    }

    //进入我的诊室
    @JavascriptInterface
    public void my_consult_room() {
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //保存病历
    @JavascriptInterface
    public void debug(String debugstr) {
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //保存病历
    @JavascriptInterface
    public void addbli(String bli, String blimsg) {
        finish();
//        MyPermission myPermission=new MyPermission();
//        myPermission.storagepermission();

    }

    //进入我的诊室
    @JavascriptInterface
    public void call(String when, String toast, String params, String command) {
        if (!TextUtils.isEmpty(command)) {
            if (command.equals("finish")) {
                ((Activity) getContext()).finish();
            }
        }
    }

    @JavascriptInterface
    public void finish() {
        ((Activity) getContext()).finish();
    }

}
